﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace WsusWebAdmin.Web.Helpers
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class JsonRequestAttribute : ActionFilterAttribute, IActionFilter
    {
        public JsonRequestAttribute(string parameterName, Type parameterType)
            : base()
        {
            ParameterName = parameterName;
            ParameterType = parameterType;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {            
            if (filterContext.HttpContext.Request.ContentType.Contains("json"))
            {
                var serializer = new DataContractJsonSerializer(ParameterType);
                var data = serializer.ReadObject(filterContext.HttpContext.Request.InputStream);
                filterContext.ActionParameters[ParameterName] = data;
            }
        }

        public Type ParameterType { get; set; }

        public string ParameterName { get; set; }
    }
}